<?php

namespace App\Modules\Popularize\Platform;

use App\Http\Model\Device;
use App\Http\Model\UserRegisterLog;

class PlatformAlihuichuan implements PlatformInterface
{

    protected $callback;
    protected $platform;
    protected $device;
    protected $userId;

    const ACTIVITE_EVENT = 1;
    const REGISTER_EVENT = 27;
    const PAY_EVENT = 1000;

    public function __construct($callback, $platfrom, $device, $userId)
    {
        $this->callback = $callback;
        $this->platform = $platfrom;
        $this->device = $device;
        $this->userId = $userId;
    }

    public function active(): ?bool
    {
        $requestData = $this->_buildRequestData(self::ACTIVITE_EVENT);
        if (empty($requestData)) {
            return false;
        }
        $params = json_decode(json_encode($this->device), true);
        $params = $this->_checkField($params);
        try {
            if (isset($this->device->guid) && $this->device->guid != '') {
                //查询是否存在设备信息，如果存在就说明设备已经激活
                $deviceModel = new Device();
                $deviceInfo = $deviceModel->getByGuid($this->device->guid);
                if (!empty($deviceInfo)) {
                    write_log('Platform', 'platform_aliHuichuan', ["设备已存在", $params]);
                    return false;
                }

                $deviceModel->save($params);

                //获取用户注册并修改渠道
                $model = new UserRegisterLog();
                $userRegisterLog = $model->findRecordByGuid($this->device->guid, ['user_id']);
                if ($userRegisterLog && $this->platform != '' && is_numeric($userRegisterLog['platform']) && $userRegisterLog['platform'] == $userRegisterLog['channel_id']) {
                    $model->updatePlatform($userRegisterLog['user_id'], $this->platform);
                }

                write_log('Platform', 'platform_aliHuichuan', ["保存设备信息成功", $params]);
                return $this->_report(self::ACTIVITE_EVENT, $requestData);
            }
        } catch (\Exception $e) {
            write_log('Platform', 'platform_aliHuichuan', ["保存设备信息失败", $params, $e->getMessage()]);
            return false;
        }
        return true;
    }

    public function regist(): ?bool
    {
        $requestData = $this->_buildRequestData(self::REGISTER_EVENT);
        if (empty($requestData)) {
            return false;
        }
        return $this->_report(self::REGISTER_EVENT, $requestData);
    }

    public function pay($amount = 0): ?bool
    {
        $requestData = $this->_buildRequestData(self::PAY_EVENT, $amount);
        if (empty($requestData)) {
            return false;
        }
        return $this->_report(self::PAY_EVENT, $requestData);
    }

    /**
     * 获取设备信息
     */
    public function getDevice()
    {
        return $this->device;
    }

    private function _buildRequestData($type, $payAmount = 0)
    {
        return [
            'type' => $type,
            'money' => $payAmount,
            'event_time' => time() * 1000,
            'idfa' => $this->device->idfa ?? "",
            'imei_sum' => isset($this->device->imei) ? md5($this->device->imei) : "",
            'oaid' => $this->device->oaid ?? "",
        ];
    }

    //上报服务器
    private function _report($type, $requestData)
    {
        if (empty($requestData)) {
            return false;
        }

        $callback = $this->callback . "&type=" . $type;
        try {
            $header = ['Content-Type' => 'application/json'];
            $result = curl_request($callback, $requestData, 'json', 'GET', $header);
            write_log('Advertisement', 'platform_aliHuichuan_success', [$type, $callback, $requestData, $result]);
        } catch (\Exception $exception) {
            write_log('Advertisement', 'platform_aliHuichuan_error', [$type, $callback, $requestData, $result]);
            return false;
        }
        $result = json_decode($result);

        return isset($result->code) && $result->code == 0;
    }

    protected function _checkField($params = [])
    {
        do {
            $checkField = ['cid', 'aid', 'callback', 'advertiser_id', 'guid', 'idfa', 'version_no', 'os_name', 'device', 'channel_id', 'platform', 'imei', 'oaid', 'adid', 'conv_ext', 'client_ip'];
            if (empty($params)) {
                break;
            }

            $inputParams = [];
            foreach ($checkField as $field) {
                if (array_key_exists($field, $params)) {
                    $inputParams[$field] = $params[$field];
                }
            }

            $params = $inputParams;
        } while (false);

        return $params;
    }

}
